var util = require('../../utils/util.js');
var user = require('../../utils/user.js');
var api = require('../../config/api.js');
var app = getApp();
var lastTime = null;

Page({
  data: {
    isMultiOrderModel: 0,
    shoppingCartList: [],
    orderAddress: {},
    mendian: {},
    couponnum: 0, // 可用的优惠券数量
    shangpinheji: 0.00, //商品总价
    yunfei: 0.00, //快递费
    couponmiane: 0.00, //优惠券的价格
    manjianjine: 0.00,
    yunxuyouhuiquan: 1,
    shifujine: 0.00, //实际需要支付的总价
    shoppingcartid: '',
    addressId: '',
    couponId: '',
    mendianid: '',
    type: 0,
    message: '',
    orderId: ''
  },
  onLoad: function (options) {
    let that = this;
    wx.setStorageSync('couponId', '');
    var shoppingcartid = wx.getStorageSync('shoppingcartid');
    if (shoppingcartid) {
      that.setData({
        shoppingcartid: shoppingcartid
      });
    }
    that.getorderInfo();
  },

  //获取order信息
  getorderInfo: function () {
    let that = this;
    util.request(api.Order, {
      shoppingcartid: that.data.shoppingcartid
    }, 'Post').then(function (res) {
      if (res.result == 1) {
        that.setData({
          shoppingCartList: res.data.shoppingCartList,
          couponnum: res.data.couponnum,
          shangpinheji: res.data.shangpinheji,
          yunfei: res.data.yunfei,
          manjianjine: res.data.manjianjine,
          yunxuyouhuiquan: res.data.yunxuyouhuiquan
        });
        if (that.data.type == 0) {
          that.setData({
            shifujine: that.data.shangpinheji + that.data.yunfei - that.data.couponmiane - that.data.manjianjine
          });
        } else {
          that.setData({
            shifujine: that.data.shangpinheji - that.data.couponmiane - that.data.manjianjine
          });
        }
      }
      wx.hideLoading();
    });
  },

  //选择地址或优惠券回调
  getaddressorcoupon: function () {
    let that = this;
    util.request(api.OrderAddressOrCoupon, {
      addressId: that.data.addressId,
      couponId: that.data.couponId,
      mendianid: that.data.mendianid,
    }, 'Post').then(function (res) {
      if (res.result == 1) {
        var _couponmiane = 0.00;
        if (res.data.coupon) {
          _couponmiane = res.data.coupon.miane
          that.setData({
            couponmiane: _couponmiane
          });
        }
        if (res.data.orderAddress) {
          that.setData({
            orderAddress: res.data.orderAddress
          });
        }
        if (res.data.mendian) {
          that.setData({
            mendian: res.data.mendian
          });
        }
        if (that.data.type == 0) {
          that.setData({
            shifujine: that.data.shangpinheji + that.data.yunfei - that.data.couponmiane - that.data.manjianjine
          });
        } else {
          that.setData({
            shifujine: that.data.shangpinheji - that.data.couponmiane - that.data.manjianjine
          });
        }
      }
      wx.hideLoading();
    });
  },

  switchTab: function (e) {
    let that = this;
    that.setData({
      type: e.currentTarget.dataset.index,
    });
    if (that.data.type == 0) {
      that.setData({
        shifujine: that.data.shangpinheji + that.data.yunfei - that.data.couponmiane - that.data.manjianjine
      });
    } else {
      that.setData({
        shifujine: that.data.shangpinheji - that.data.couponmiane - that.data.manjianjine
      });
    }
  },
  //选择收货人地址
  selectAddress() {
    wx.navigateTo({
      url: '/pages/ucenter/address/address',
    })
  },
  //选择门店地址
  selectMendian() {
    wx.navigateTo({
      url: '/pages/ucenter/guanli/mendian/mendian',
    })
  },
  selectCoupon() {
    let that = this;
    if (that.data.yunxuyouhuiquan == 0) {
      wx.showModal({
        title: '提示',
        content: '满减优惠活动期间暂不能使用优惠券哟，亲！',
        success(res) {
          if (res.confirm) {
            return false;
          } else if (res.cancel) {
            return false;
          }
        }
      })
    } else {
      wx.navigateTo({
        url: '/pages/ucenter/couponSelect/couponSelect',
      })
    }
  },
  bindMessageInput: function (e) {
    this.setData({
      message: e.detail.value
    });
  },
  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示
    var that = this;
    try {

      var addressid = wx.getStorageSync('addressid');
      if (addressid) {
        that.setData({
          'addressId': addressid
        });
      }

      var mendianid = wx.getStorageSync('mendianid');
      if (mendianid) {
        that.setData({
          'mendianid': mendianid
        });
      }

      var couponId = wx.getStorageSync('couponId');
      if (couponId) {
        that.setData({
          'couponId': couponId
        });
      }
    } catch (e) {
      // Do something when catch error
      console.log(e);
    }
    that.getaddressorcoupon();
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  submitOrder: function () {
    let that = this;
    var submityunfei = 0;
    if (that.data.shoppingCartList.length == 0) {
      util.showErrorToast('商品不能为空');
      return false;
    }
    if (that.data.type == 0) {
      if (that.data.addressId == '') {
        util.showErrorToast('请选择收货地址');
        return false;
      }
      submityunfei = that.data.yunfei;
    }
    if (that.data.type == 1) {
      if (!that.data.mendian.id) {
        util.showErrorToast('请选择门店地址');
        return false;
      }
      submityunfei = 0;
    }
    util.jhxLoadShow("正在下单，请稍后...");
    let nowTime = +new Date();
    if (nowTime - lastTime > 5000 || !lastTime) { //5秒内避免重复提交订单
      lastTime = nowTime;
    } else {
      return false;
    }
    util.request(api.OrderSubmit, {
      shoppingcartid: that.data.shoppingcartid,
      addressId: that.data.addressId,
      mendianid: that.data.mendianid,
      couponId: that.data.couponId,
      message: that.data.message,
      shangpinheji: that.data.shangpinheji,
      shifujine: that.data.shifujine,
      yunfei: submityunfei,
      shouhuotype: that.data.type,
    }, 'POST').then(res => {
      util.jhxLoadHide();
      that.setData({
        orderId: res.data.orderId
      });
      if (res.result == 1) {
        let memberUserid = wx.getStorageSync('memberUserid');
        util.request(api.OrderPrepay, {
          memberUserid: memberUserid,
          orderId: that.data.orderId,
          amount_total: that.data.shifujine
        }, 'POST').then(function (res) {
          if (res.result == 1) {
            const payParam = res.data;
            wx.requestPayment({
              'timeStamp': payParam.timeStamp,
              'nonceStr': payParam.nonceStr,
              'package': payParam.package,
              'signType': payParam.signType,
              'paySign': payParam.paySign,
              'success': function (res) {
                console.log("支付过程成功");
                user.getcartgoodnum().then(res => {
                  var cartnum = res.data.icount + '';
                  wx.setStorageSync('cartnum', cartnum);
                  wx.setTabBarBadge({
                    index: 2,
                    text: cartnum
                  })
                });
                wx.redirectTo({
                  url: '/pages/payResult/payResult?status=1&orderId=' + that.data.orderId
                });
              },
              'fail': function (res) {
                console.log("支付过程失败")
                wx.redirectTo({
                  url: '/pages/payResult/payResult?status=0&orderId=' + that.data.orderId
                });
              },
              'complete': function (res) {
                console.log("支付过程结束");
                wx.requestSubscribeMessage({
                  tmplIds: app.globalData.tmplIds,
                  success(res) {
                    util.request(api.Ordermessage, {
                      orderId: that.data.orderId
                    }, 'POST').then(function (res) {});
                  }
                })
              }
            });
          } else {
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=0&orderId=' + that.data.orderId
            });
          }
        });
      } else {
        wx.redirectTo({
          url: '/pages/payResult/payResult?status=0&orderId=' + that.data.orderId
        });
      }
    });
  }
});